﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;

namespace RAP.Framework.Libary.Utils.Collection.Iterator
{
    /// <summary>
    /// 
    /// </summary>
    public class RecursionIteratorContext : IDisposable
    {
        /// <summary>
        /// 
        /// </summary>
        public string Expression { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string Field { get; set; }

        private object _dataSource = null;
        /// <summary>
        /// 
        /// </summary>
        public object DataSource
        {
            get
            {
                return _dataSource;
            }
            set
            {
                _dataSource = value;
                _enumerator = null;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public object CurrentData { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public int CurrentIndex { get; set; }

        private IEnumerator _enumerator = null;
        /// <summary>
        /// 
        /// </summary>
        public IEnumerator Enumerator
        {
            get
            {
                if ( !this.IsCollection || this.DataSource == null )
                {
                    return null;
                }
                if ( _enumerator == null )
                {
                    _enumerator = ( this.DataSource as ICollection ).GetEnumerator();
                }
                return _enumerator;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public bool IsCollection { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public bool IsFinished { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public RecursionIteratorContext ParentItem { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public RecursionIteratorContext ChildItem { get; set; }

        /// <summary>
        /// 存放附加数据的属性
        /// </summary>
        public object Tag { get; set; }

        /// <summary>
        /// 刷新子节点的数据源
        /// </summary>
        public void RefreshChildItems ()
        {
            var childItem = ChildItem;
            while ( childItem != null )
            {
                childItem.Refresh();
                childItem = childItem.ChildItem;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        public void Refresh ()
        {
            DataSource = null;
            CurrentData = null;
            CurrentIndex = 0;
        }

        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose ()
        {
            DataSource = null;
            ParentItem = null;
            ChildItem = null;
            Tag = null;
        }
    }
}
